<template>
  <div class="visit-feedback">
    <el-card :body-style="{ padding: '20px' }">
      <template #header>
        <div class="card-header">
          <span>走访结果反馈</span>
        </div>
      </template>

      <!-- 走访计划选择 -->
      <div class="form-section">
        <h3 class="section-title">选择走访计划</h3>
        <el-form-item label="" prop="selectedPlanId">
          <el-select
            v-model="selectedPlanId"
            placeholder="请选择要反馈的走访计划"
            style="width: 100%"
          >
            <el-option
              v-for="plan in availablePlans"
              :key="plan.id"
              :label="plan.name"
              :value="plan.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </div>

      <!-- 选定计划信息展示 -->
      <div v-if="selectedPlan">
        <!-- 计划基本信息 -->
        <div class="form-section">
          <h3 class="section-title">计划基本信息</h3>
          <div class="info-grid">
            <div class="info-item">
              <label>计划名称:</label>
              <span>{{ selectedPlan.name }}</span>
            </div>
            <div class="info-item">
              <label>客户名称:</label>
              <span class="clickable-customer" @click="viewCustomerDetail"
                >{{ selectedPlan.customerName }}
                <el-tag type="primary" size="small">查看详情</el-tag></span
              >
            </div>
            <div class="info-item">
              <label>走访时间:</label>
              <span>{{ selectedPlan.visitDate }}</span>
            </div>
            <div class="info-item">
              <label>客户经理:</label>
              <span>{{ selectedPlan.manager }}</span>
            </div>
          </div>
        </div>

        <!-- 反馈方式选择 -->
        <div class="form-section">
          <h3 class="section-title">反馈方式</h3>
          <div class="method-tabs">
            <el-tabs v-model="activeTab" @tab-click="handleTabChange">
              <el-tab-pane label="文本输入" name="text"></el-tab-pane>
              <el-tab-pane label="录音上传" name="audio"></el-tab-pane>
              <el-tab-pane label="走访助手" name="assistant"></el-tab-pane>
            </el-tabs>
          </div>
        </div>

        <!-- 文本输入区域 -->
        <div v-if="activeTab === 'text'" class="form-section">
          <h3 class="section-title">走访总结</h3>
          <el-input
            v-model="feedbackForm.summary"
            type="textarea"
            placeholder="请输入本次走访的详细总结..."
            :rows="8"
          ></el-input>
        </div>

        <!-- 录音上传区域 -->
        <div v-if="activeTab === 'audio'" class="form-section">
          <h3 class="section-title">录音上传</h3>
          <div class="upload-container">
            <el-upload
              ref="upload"
              :headers="uploadHeaders"
              :data="uploadData"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="onUploadSuccess"
              :on-error="onUploadError"
              class="upload-demo"
            >
              <el-button type="primary" :loading="uploading">
                {{ uploading ? "上传中" : "上传录音文件" }}
              </el-button>
            </el-upload>
            <div class="upload-tips">
              <p>• 支持MP3、WAV、OGG格式</p>
              <p>• 文件大小不超过50MB</p>
              <p>• 录音将自动转换为文本并生成走访总结</p>
            </div>
          </div>
          <div v-if="audioFileName" class="uploaded-file">
            <el-tag type="success">已上传：{{ audioFileName }}</el-tag>
            <el-button type="text" @click="removeAudioFile">移除</el-button>
          </div>
        </div>

        <!-- 走访助手集成 -->
        <div v-if="activeTab === 'assistant'" class="form-section">
          <h3 class="section-title">走访助手</h3>
          <div class="assistant-section">
            <el-button type="primary" @click="openAssistantModal"
              >打开走访助手</el-button
            >
            <p class="assistant-tip">
              通过走访助手的对话功能，自动生成走访总结和关键信息
            </p>
          </div>
        </div>

        <!-- 特定目标信息录入 -->
        <div class="form-section">
          <h3 class="section-title">走访目标信息录入</h3>
          <div
            v-for="(target, targetIndex) in selectedPlan.targets"
            :key="target.id"
            class="target-item"
          >
            <div class="target-header">
              <span class="target-title"
                >目标 {{ targetIndex + 1 }} {{ target.name }}</span
              >
            </div>
            <div class="target-content">
              <!-- 产品推荐录入 -->
              <div
                v-if="target.type === 'PRODUCT_MARKETING'"
                class="product-recommendation"
              >
                <label>产品意向录入：</label>
                <div class="product-list">
                  <div
                    v-for="(product, index) in target.products"
                    :key="index"
                    class="product-item"
                  >
                    <div class="product-info">
                      <div class="product-name">{{ product.name }}</div>
                    </div>
                    <div class="product-intention">
                      <el-radio-group
                        v-model="product.intention"
                        @change="
                          updateProductIntention(
                            target.id,
                            product.id,
                            product.intention
                          )
                        "
                      >
                        <el-radio :label="'接受'">接受</el-radio>
                        <el-radio :label="'不接受'">不接受</el-radio>
                        <el-radio :label="'再考虑'">再考虑</el-radio>
                      </el-radio-group>
                      <div v-if="product.intention" class="selected-intention">
                        意向: {{ product.intention }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 关键人信息收集录入 -->
              <div
                v-if="target.type === 'KEY_PERSON_COLLECTION'"
                class="key-persons-section"
              >
                <label>关键人信息录入：</label>
                <el-table :data="target.keyPersons" style="width: 100%">
                  <el-table-column prop="name" label="姓名" width="120">
                    <template #default="scope">
                      <el-input
                        v-model="scope.row.name"
                        placeholder="请输入姓名"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="department" label="部门" width="150">
                    <template #default="scope">
                      <el-input
                        v-model="scope.row.department"
                        placeholder="请输入部门"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="contactNumber"
                    label="联系方式"
                    width="150"
                  >
                    <template #default="scope">
                      <el-input
                        v-model="scope.row.contactNumber"
                        placeholder="请输入联系方式"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="position" label="职务" width="120">
                    <template #default="scope">
                      <el-input
                        v-model="scope.row.position"
                        placeholder="请输入职务"
                      ></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="80" fixed="right">
                    <template #default="scope">
                      <el-button
                        @click="removeKeyPerson(target.id, scope.$index)"
                        type="text"
                        size="small"
                        >移除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
                <el-button
                  @click="addKeyPerson(target.id)"
                  type="primary"
                  size="small"
                  style="margin-top: 10px"
                  >添加关键人</el-button
                >
              </div>
            </div>
          </div>
        </div>

        <!-- 待办事项记录 -->
        <div class="form-section">
          <h3 class="section-title">待办事项记录</h3>
          <el-table :data="feedbackForm.todos" style="width: 100%">
            <el-table-column prop="content" label="待办内容" min-width="200">
              <template #default="scope">
                <el-input
                  v-model="scope.row.content"
                  placeholder="请输入待办内容"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="dueDate" label="截止日期" width="150">
              <template #default="scope">
                <el-date-picker
                  v-model="scope.row.dueDate"
                  type="date"
                  placeholder="选择截止日期"
                  style="width: 100%"
                ></el-date-picker>
              </template>
            </el-table-column>
            <el-table-column prop="completed" label="是否完成" width="100">
              <template #default="scope">
                <el-switch v-model="scope.row.completed"></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" fixed="right">
              <template #default="scope">
                <el-button
                  @click="removeTodo(scope.$index)"
                  type="text"
                  size="small"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-button
            @click="addTodo"
            type="primary"
            size="small"
            style="margin-top: 10px"
            >添加待办事项</el-button
          >
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="submitFeedback">提交反馈</el-button>
        </div>
      </div>
    </el-card>

    <!-- 走访助手模态框 -->
    <el-dialog
      title="走访助手"
      v-model="showAssistantModal"
      width="800px"
      :fullscreen="isAssistantFullscreen"
    >
      <div class="assistant-modal-content">
        <VisitAssistant @feedback-generated="handleAssistantFeedback" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="toggleAssistantFullscreen">
            {{ isAssistantFullscreen ? "退出全屏" : "全屏显示" }}
          </el-button>
          <el-button @click="showAssistantModal = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
// import { useVisitStore } from "@/store/visit";
import VisitAssistant from "./VisitAssistant.vue";

// 类型定义
interface TodoItem {
  id: string;
  content: string;
  completed: boolean;
  dueDate: string;
}

interface Product {
  id: string;
  name: string;
  intention: string;
}

interface KeyPerson {
  id: string;
  name: string;
  department: string;
  contactNumber: string;
  position: string;
}

interface Target {
  id: string;
  name: string;
  type: string;
  products?: Product[];
  keyPersons?: KeyPerson[];
  completed: boolean;
  remark: string;
}

interface VisitPlan {
  id: string;
  name: string;
  customerName: string;
  visitDate: string;
  manager: string;
  targets: Target[];
}

interface FeedbackForm {
  summary: string;
  todos: TodoItem[];
}

interface AssistantFeedback {
  summary: string;
}

// 状态管理
const router = useRouter();
// const visitStore = useVisitStore()

// 可用的走访计划
const availablePlans = ref<VisitPlan[]>([
  {
    id: "plan1",
    name: "季度客户回访计划 - ABC贸易有限公司",
    customerName: "ABC贸易有限公司",
    visitDate: "2023-07-10",
    manager: "张三",
    targets: [
      {
        id: "target1",
        name: "产品营销",
        type: "PRODUCT_MARKETING",
        products: [
          {
            id: "product1",
            name: "企业宽带增值套餐",
            intention: "",
          },
          {
            id: "product2",
            name: "企业云通信平台",
            intention: "",
          },
          {
            id: "product3",
            name: "物联网智能连接服务",
            intention: "",
          },
        ],
        completed: false,
        remark: "",
      },
      {
        id: "target2",
        name: "关键人信息收集",
        type: "KEY_PERSON_COLLECTION",
        keyPersons: [
          {
            id: "person1",
            name: "",
            department: "",
            contactNumber: "",
            position: "",
          },
        ],
        completed: false,
        remark: "",
      },
    ],
  },
  {
    id: "plan2",
    name: "新客户开发计划 - 科技有限公司",
    customerName: "科技有限公司",
    visitDate: "2023-07-15",
    manager: "张三",
    targets: [
      {
        id: "target3",
        name: "产品营销",
        type: "PRODUCT_MARKETING",
        products: [
          {
            id: "product4",
            name: "企业云通信平台",
            intention: "",
          },
          {
            id: "product5",
            name: "5G企业专网",
            intention: "",
          },
        ],
        completed: false,
        remark: "",
      },
    ],
  },
]);

// 选中的走访计划ID
const selectedPlanId = ref("");

// 选中的走访计划详情
const selectedPlan = ref<VisitPlan | null>(null);

// 反馈表单数据
const feedbackForm = reactive<FeedbackForm>({
  summary: "",
  todos: [
    {
      id: "todo1",
      content: "",
      completed: false,
      dueDate: "",
    },
  ],
});

// 活跃的标签页
const activeTab = ref("text");

// 上传相关
// const uploadRef = ref<any>(null);
const uploading = ref(false);
const uploadHeaders = ref<Record<string, string>>({});
const uploadData = ref<Record<string, any>>({});
const audioFileName = ref("");

// 走访助手模态框
const showAssistantModal = ref(false);
const isAssistantFullscreen = ref(false);

// 监听选中的计划变化
watch(selectedPlanId, (newVal) => {
  if (newVal) {
    // 深拷贝选中的计划，避免直接修改原始数据
    const plan = availablePlans.value.find((p) => p.id === newVal);
    if (plan) {
      selectedPlan.value = JSON.parse(JSON.stringify(plan));
      resetFeedbackForm();
    }
  } else {
    selectedPlan.value = null;
  }
});

// 查看客户详情
const viewCustomerDetail = () => {
  if (selectedPlan.value) {
    router.push(`/customer/${selectedPlan.value.id}`);
  }
};

// 重置反馈表单
const resetFeedbackForm = () => {
  feedbackForm.summary = "";
  feedbackForm.todos = [
    {
      id: "todo1",
      content: "",
      completed: false,
      dueDate: "",
    },
  ];
  activeTab.value = "text";
  audioFileName.value = "";
};

// 添加待办事项
const addTodo = () => {
  const newId = Date.now().toString();
  feedbackForm.todos.push({
    id: newId,
    content: "",
    completed: false,
    dueDate: "",
  });
  ElMessage.success("已添加新的待办事项");
};

// 移除待办事项
const removeTodo = (index: number) => {
  if (feedbackForm.todos.length > 1) {
    feedbackForm.todos.splice(index, 1);
    ElMessage.success("已移除待办事项");
  } else {
    ElMessage.warning("至少保留一项待办事项");
  }
};

// 处理标签页切换
const handleTabChange = (tab: any) => {
  activeTab.value = tab.name;
};

// 上传前检查
const beforeUpload = (file: File) => {
  const isAudio = file.type.includes("audio/");
  const isLt50M = file.size / 1024 / 1024 < 50;

  if (!isAudio) {
    ElMessage.error("只能上传音频文件!");
    return false;
  }
  if (!isLt50M) {
    ElMessage.error("文件大小不能超过50MB!");
    return false;
  }

  uploading.value = true;
  return true;
};

// 上传成功
const onUploadSuccess = (_response: any, file: File) => {
  uploading.value = false;
  audioFileName.value = file.name;
  // 模拟从录音生成文本
  setTimeout(() => {
    feedbackForm.summary =
      "根据录音内容自动生成的走访总结：客户对企业云通信平台表示兴趣，希望提供详细方案和报价。客户提到近期有网络升级计划，需要后续跟进。";
    ElMessage.success("录音上传成功并已转换为文本");
  }, 1000);
};

// 上传失败
const onUploadError = (error: any) => {
  uploading.value = false;
  ElMessage.error("上传失败，请重试");
  console.error("Upload error:", error);
};

// 移除已上传的音频文件
const removeAudioFile = () => {
  audioFileName.value = "";
  feedbackForm.summary = "";
  ElMessage.success("文件已移除");
};

// 打开走访助手模态框
const openAssistantModal = () => {
  showAssistantModal.value = true;
};

// 切换助手全屏显示
const toggleAssistantFullscreen = () => {
  isAssistantFullscreen.value = !isAssistantFullscreen.value;
};

// 处理助手生成的反馈
const handleAssistantFeedback = (feedback: AssistantFeedback) => {
  // 这里应该根据助手返回的结果更新表单
  feedbackForm.summary = feedback.summary || "";
  // 如果有助手分析的产品意向或关键人信息，也可以在这里更新
};

// 更新产品意向
const updateProductIntention = (
  targetId: string,
  productId: string,
  intention: string
) => {
  if (selectedPlan.value) {
    const target = selectedPlan.value.targets.find((t) => t.id === targetId);
    if (target && target.products) {
      const product = target.products.find((p) => p.id === productId);
      if (product) {
        product.intention = intention;
      }
    }
  }
};

// 添加关键人
const addKeyPerson = (targetId: string) => {
  if (selectedPlan.value) {
    const target = selectedPlan.value.targets.find((t) => t.id === targetId);
    if (target && target.keyPersons) {
      const newId = Date.now().toString();
      target.keyPersons.push({
        id: newId,
        name: "",
        department: "",
        contactNumber: "",
        position: "",
      });
      ElMessage.success("已添加新的关键人行");
    }
  }
};

// 移除关键人
const removeKeyPerson = (targetId: string, index: number) => {
  if (selectedPlan.value) {
    const target = selectedPlan.value.targets.find((t) => t.id === targetId);
    if (target && target.keyPersons && target.keyPersons.length > 1) {
      target.keyPersons.splice(index, 1);
      ElMessage.success("已移除关键人行");
    } else if (target && target.keyPersons && target.keyPersons.length === 1) {
      // 保留至少一行
      ElMessage.warning("至少保留一行关键人信息");
    }
  }
};

// 重置表单
const resetForm = () => {
  resetFeedbackForm();
  // 重置选中计划的目标状态
  if (selectedPlan.value && selectedPlan.value.targets) {
    selectedPlan.value.targets.forEach((target) => {
      if (target.products) {
        target.products.forEach((product) => {
          product.intention = "";
        });
      }
      if (target.keyPersons) {
        target.keyPersons = [
          {
            id: "person1",
            name: "",
            department: "",
            contactNumber: "",
            position: "",
          },
        ];
      }
    });
  }
};

// 提交反馈
const submitFeedback = async () => {
  if (!selectedPlan.value) {
    ElMessage.error("请先选择走访计划");
    return;
  }

  // 构建提交的数据
  const feedbackData = {
    planId: selectedPlanId.value,
    summary: feedbackForm.summary,
    audioFile: audioFileName.value,
    todos: feedbackForm.todos,
    // 在提交前过滤掉不需要的字段
    targets: selectedPlan.value.targets.map((target) => {
      // 深拷贝target对象，避免修改原始数据
      const cleanTarget = JSON.parse(JSON.stringify(target));
      // 删除不需要的字段
      delete cleanTarget.completed;
      delete cleanTarget.remark;
      return cleanTarget;
    }),
    submitTime: new Date().toISOString(),
  };

  try {
    // 在实际应用中，这里应该调用API提交数据
    console.log("提交的反馈数据:", feedbackData);

    // 模拟提交成功
    ElMessage.success("走访反馈提交成功");
  } catch (error) {
    ElMessage.error("提交失败，请重试");
    console.error("提交反馈失败:", error);
  }
};

// 组件挂载时的操作
onMounted(() => {
  // 可以在这里初始化数据或执行其他操作
});
</script>

<style lang="scss" scoped>
.visit-feedback {
  font-size: 14px;
  
  // 表单区块
  .form-section {
    margin-bottom: 30px;
    
    .section-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid $border-color;
    }
  }
  
  // 信息网格
  .info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 15px;
    
    .info-item {
      display: flex;
      flex-direction: column;
      
      label {
        color: $text-secondary;
        font-size: 12px;
        margin-bottom: 4px;
      }
      
      span {
        color: $text-color;
      }
      
      // 可点击的客户名称样式
      .clickable-customer {
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        transition: color 0.3s;
        
        &:hover {
          color: $primary-color;
        }
      }
    }
  }
  
  // 方法标签页
  .method-tabs {
    margin-top: 10px;
  }
  
  // 录音上传区域
  .upload-container {
    display: flex;
    align-items: flex-start;
    gap: 20px;
    margin-bottom: 15px;
    
    .upload-tips {
      flex: 1;
      color: $text-secondary;
      font-size: 12px;
      
      p {
        margin: 5px 0;
      }
    }
  }
  
  .uploaded-file {
    margin-top: 10px;
    display: flex;
    align-items: center;
    gap: 10px;
  }
  
  // 走访助手区域
  .assistant-section {
    padding: 20px;
    background-color: $bg-light;
    border-radius: 8px;
    text-align: center;
    
    .assistant-tip {
      margin-top: 10px;
      color: $text-secondary;
      font-size: 12px;
    }
  }
  
  // 目标项
  .target-item {
    border: 1px solid $border-color;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
    
    .target-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid $border-color;
      
      .target-title {
        font-weight: bold;
        color: $text-color;
      }
    }
    
    .target-content {
      display: flex;
      flex-direction: column;
      gap: 15px;
      
      // 目标字段
      .target-field {
        display: flex;
        flex-direction: column;
        
        label {
          color: $text-secondary;
          font-size: 12px;
          margin-bottom: 4px;
        }
      }
      
      // 产品推荐区域样式
      .product-recommendation {
        padding: 16px;
        background-color: $bg-light;
        border-radius: 8px;
        
        .product-list {
          display: flex;
          flex-direction: column;
          gap: 12px;
          margin-top: 8px;
          
          .product-item {
            padding: 12px;
            background-color: $bg-white;
            border: 1px solid #e6e6e6;
            border-radius: 6px;
            display: flex;
            flex-direction: column;
            gap: 12px;
            
            .product-info {
              flex: 1;
              
              .product-name {
                font-weight: bold;
                font-size: 16px;
                color: $text-color;
                margin-bottom: 4px;
              }
            }
            
            .product-intention {
              display: flex;
              flex-direction: column;
              gap: 8px;
              margin-top: 8px;
              
              .selected-intention {
                color: $success-color;
                font-size: 14px;
                font-weight: 500;
              }
            }
          }
        }
      }
      
      // 关键人信息样式
      .key-persons-section {
        margin-bottom: 20px;
      }
    }
  }
  
  // 通用目标样式
  .target-common {
    margin-top: 20px;
  }
  
  // 操作按钮
  .form-actions {
    margin-top: 20px;
    text-align: right;
  }
  
  // 助手模态框内容
  .assistant-modal-content {
    height: 70vh;
    overflow-y: auto;
  }
}
</style>
